package com.uinnova.product.eam.workable.listener;

import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.HistoryService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component("getApprovedUserListener")
public class GetApprovedUserListener implements ExecutionListener {

    @Resource
    private HistoryService historyService;

    @Override
    public void notify(DelegateExecution execution) {
        //获取流程实例id
        String processInstanceId = execution.getProcessInstanceId();
        //根据流程实例id获取这个流程已完成的任务
        List<HistoricTaskInstance> list = historyService
                .createHistoricTaskInstanceQuery()
                .processInstanceId(processInstanceId)
                .taskVariableValueLikeIgnoreCase("pass","%pass%")
                .finished()
                .list();
        List<String> userCodes = list.stream().map(HistoricTaskInstance::getAssignee).distinct().collect(Collectors.toList());
        log.info("审批用户：{}", userCodes);
        Map<String, Object> variables = execution.getVariables();
        if (!CollectionUtils.isEmpty(userCodes)) {
            log.info("审批用户：{}", userCodes);
            String currentActivityId = execution.getCurrentActivityId();
            log.info("执行器id{}", currentActivityId);
            variables.put("assigneeList", userCodes);
        }
        execution.setVariables(variables);

    }
}
